export default {
    data() {
        return {
            userInfo: null,
            loading: true,
            refreshing: false,
            page: 1,
            limit: 10,
            total: 0,
            hasMore: true,
            filterParams: {
                title: '',
                category: '',
                status: '',
                startDate: '',
                endDate: ''
            }
        }
    },
    methods: {
        // 增强版用户信息获取 - 多种验证方式
        getUserInfo() {
            console.log('开始获取用户信息');
            
            // 1. 首先从本地存储获取
            const userInfoStr = uni.getStorageSync('userInfo');
            const token = uni.getStorageSync('uni_id_token');
            
            if (userInfoStr) {
                try {
                    let userInfo = JSON.parse(userInfoStr);
                    // 确保有正确的用户ID
                    if (!userInfo._id) {
                        userInfo._id = userInfo.userId || userInfo.id || userInfo._openid;
                    }
                    this.userInfo = userInfo;
                    console.log('从本地存储获取到用户信息:', this.userInfo);
                    
                    // 验证token是否有效
                    if (!token) {
                        console.warn('本地token不存在，尝试重新获取用户信息');
                        this.getUserInfoFromCloud();
                        return;
                    }
                    
                    this.checkPermission();
                } catch (e) {
                    console.error('解析用户信息失败', e);
                    this.handleError('获取用户信息失败');
                    this.getUserInfoFromCloud();
                }
            } else {
                console.log('本地无用户信息，从云端获取');
                this.getUserInfoFromCloud();
            }
        },

        // 增强版云端用户信息获取
        getUserInfoFromCloud() {
            uni.showLoading({
                title: '加载中...'
            });
            
            // 获取token
            const token = uni.getStorageSync('uni_id_token');
            
            uniCloud.callFunction({
                name: 'user',
                data: {
                    action: 'getUserInfo',
                    token: token
                },
                success: (res) => {
                    uni.hideLoading();
                    console.log('云函数获取用户信息结果:', res.result);
                    
                    if (res.result.code === 0 && res.result.data) {
                        // 标准化用户信息格式
                        this.userInfo = {
                            ...res.result.data,
                            _id: res.result.data.userId || res.result.data._id
                        };
                        console.log('从云端获取用户信息成功:', this.userInfo);
                        
                        // 保存到本地存储
                        uni.setStorageSync('userInfo', JSON.stringify(this.userInfo));
                        
                        this.checkPermission();
                    } else if (res.result.code === 401) {
                        // token失效，引导用户重新登录
                        console.error('用户token已失效:', res.result.message);
                        this.handleNoPermission('登录已过期，请重新登录');
                        
                        // 清除无效的信息
                        uni.removeStorageSync('userInfo');
                        uni.removeStorageSync('uni_id_token');
                        
                        // 保存当前页面路径，便于登录后返回
                        const pages = getCurrentPages();
                        if (pages.length > 0) {
                            const currentPage = pages[pages.length - 1];
                            uni.setStorageSync('redirect_page', currentPage.route);
                        }
                        
                        // 跳转到登录页
                        setTimeout(() => {
                            uni.navigateTo({
                                url: '/pages/login/login'
                            });
                        }, 1500);
                    } else {
                        this.handleNoPermission('获取用户信息失败');
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    console.error('调用获取用户信息云函数失败', err);
                    this.handleNoPermission('网络错误');
                }
            });
        },

        // 统一的权限检查
        checkPermission() {
            if (!this.userInfo) {
                this.handleNoPermission('未登录');
                return;
            }
            
            // 检查是否为管理员
            const isadmin = this.userInfo.role == 2 || 
                this.userInfo.role == "2" || 
                this.userInfo.role == "admin" ||
                this.userInfo.role == "管理员" ||
                this.userInfo.role == "裁判监督";
            
            // 检查证书状态
            const credentialStatus = String(this.userInfo.credential_status || '').toLowerCase();
            const status = String(this.userInfo.status || '').toLowerCase();
            
            const validStatusValues = ['approved', 'valid', 'verified', 'active', '有效', '通过', '已认证', '已通过'];
            const hasValidCredential = validStatusValues.some(value => 
                credentialStatus.includes(value) || status.includes(value)
            );
            
            if (!isadmin || !hasValidCredential) {
                this.handleNoPermission('权限不足');
                return;
            }
            
            // 调用子类实现的获取列表方法
            this.fetchList();
        },

        // 统一的错误处理
        handleError(message) {
            uni.showToast({
                title: message,
                icon: 'none'
            });
        },

        // 统一的权限不足处理
        handleNoPermission(message = '无访问权限') {
            this.loading = false;
            uni.showModal({
                title: '提示',
                content: message,
                showCancel: false,
                success: () => {
                    uni.navigateBack();
                }
            });
        },

        // 统一的数据刷新
        refreshData() {
            this.refreshing = true;
            this.fetchList(false);
        },

        // 统一的加载更多
        loadMore() {
            if (this.hasMore && !this.loading) {
                this.fetchList(true);
            }
        },

        // 统一的日期格式化
        formatDate(dateStr) {
            if (!dateStr) return '';
            
            const date = new Date(dateStr);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            
            return `${year}-${month}-${day}`;
        },

        // 统一的页面导航
        navigateTo(url) {
            uni.navigateTo({
                url: url
            });
        },

        // 统一的删除确认
        confirmDelete(item, type) {
            uni.showModal({
                title: '确认删除',
                content: `确定要删除${type}"${item.title}"吗？此操作不可恢复。`,
                confirmText: '删除',
                confirmColor: '#ff4d4f',
                success: (res) => {
                    if (res.confirm) {
                        this.deleteItem(item);
                    }
                }
            });
        },

        // 统一的删除操作
        deleteItem(item) {
            uni.showLoading({
                title: '删除中...'
            });
            
            uniCloud.callFunction({
                name: `delete${this.getTypeName()}`,
                data: {
                    [`${this.getTypeName().toLowerCase()}Id`]: item._id,
                    creatorId: this.userInfo._id
                },
                success: (res) => {
                    uni.hideLoading();
                    
                    if (res.result.code === 0) {
                        uni.showToast({
                            title: '删除成功',
                            icon: 'success'
                        });
                        
                        const index = this.list.findIndex(i => i._id === item._id);
                        if (index > -1) {
                            this.list.splice(index, 1);
                        }
                    } else {
                        uni.showModal({
                            title: '删除失败',
                            content: res.result.message || '未知错误',
                            showCancel: false
                        });
                    }
                },
                fail: (err) => {
                    uni.hideLoading();
                    console.error(`删除${this.getTypeName()}失败:`, err);
                    
                    uni.showModal({
                        title: '删除失败',
                        content: '网络错误，请重试',
                        showCancel: false
                    });
                }
            });
        }
    }
} 